<template>
  <MainSlot v-loading="loading">
    <template v-slot:table>
      <div class="top config gradient-border">
        <div class="cropModel">
          <div class="label">养殖品种名称：</div>
          <div class="tagList">
            <div class="tag" :class="searchFormData.plantVarietyId == item.plantVarietyId ? 'active' : ''"
              @click="handleClickVariety(item)" v-for="item, index in varietyList" :key="index">{{
    item.plantVarietyName }}</div>
            <div class="noData" v-show="!varietyList.length">暂无数据</div>
          </div>
        </div>
        <div class="cropModel">
          <div class="label">养殖阶段名称：</div>
          <div class="tagList">
            <div class="tag" :class="searchFormData.growStageId == item.growStageId ? 'active' : ''"
              @click="handleClickGrowStage(item)" v-show="searchFormData.plantVarietyId == item.plantVarietyId"
              v-for="item, index in growthStageList" :key="index">{{ item.growStageName }}</div>
            <div class="noData" v-show="!hasGrowStageFlag">暂无数据</div>
          </div>
        </div>
      </div>
      <div class="middle config gradient-border">
        <div class="configTitle">
          <i class="el-icon-caret-right"></i>
          <span class="configLabel">配置环境条件</span>
        </div>
        <el-form ref="form" :model="form" :rules=rules label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预警名称" prop="warningName">
                <el-input v-model="form.warningName" placeholder="请输入预警名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="物联数据类型" prop="dataTypeId">
                <el-select v-model="form.dataTypeId" class="w100p" placeholder="请选择物联数据类型" @change="handleDataType">
                  <el-option v-for="item, index in dataTypeList" :key="index" :label="item.dataTypeName"
                    :value="item.dataTypeId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="下限数值" prop="lowerLimitValue">
                <el-input type="number" v-model="form.lowerLimitValue" placeholder="请输入下限"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下限造成结果" prop="lowerLimitResult">
                <el-input v-model="form.lowerLimitResult" placeholder="请输入造成结果"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="上限数值" prop="upperLimitValue">
                <el-input type="number" v-model="form.upperLimitValue" placeholder="请输入上限"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上限造成结果" prop="upperLimitResult">
                <el-input v-model="form.upperLimitResult" placeholder="请输入造成结果"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="warngingInfo">
          <div>
            <span class="label">预警条件概览：</span>
            <span>当{{ form.dataTypeName || '--' }}</span>
            <span>大于{{ form.upperLimitValue || 0 }}时,</span>
            <span>可能造成{{ form.upperLimitResult || '--' }};</span>
            <span>低于{{ form.lowerLimitValue || 0 }}时,</span>
            <span>可能造成{{ form.lowerLimitResult || '--' }}。</span>
          </div>
          <div>
            <el-button type="primary" @click="onSubmit">确认添加</el-button>
            <el-button @click="cancel">取消</el-button>
          </div>
        </div>
      </div>
      <div class="bottom config">
        <div class="configTitle">
          <i class="el-icon-caret-right"></i>
          <span class="configLabel">配置环境条件</span>
        </div>
        <div class="dataList" v-for="item, index in dataList" :key="index">
          <div><span class="label">{{ item.warningName }}</span>{{
    `当${item.dataTypeName}大于${item.upperLimitValue}时，可能造成${item.upperLimitResult};
            小于${item.lowerLimitValue}时，可能造成${item.lowerLimitResult}。` }}</div>
          <el-button type="danger" icon="el-icon-delete" circle
            @click="delById(item.environmentalWarningId)"></el-button>
        </div>
        <div class="noData" v-if="!dataList.length">暂无数据</div>
      </div>
      <div class="pagination">
        <Pagination @size-Change="handleSizeChange" :size="size"  @current-change="handleCurrentChange" :page="page" :total="total">
        </Pagination>
      </div>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import BtnSlot from '@/components/BtnSlot';
import Pagination from '@/components/Pagination';
import environmentAlarmConfig from '@/api/cropModel/environmentAlarmConfig'
import varietyManagement from '@/api/basicInformation/varietyManagement';
import growthStageDivision from '@/api/basicInformation/growthStageDivision.js';
import alarmCategoryManagement from '@/api/monitoringAlarmManagement/alarmCategoryManagement.js';
import { mapGetters } from 'vuex'
export default {
  components: { MainSlot, BtnSlot, Pagination },
  data() {
    return {
      form: {},
      page: 1,
      size:3,
      total: 100,
      hasGrowStageFlag: false,
      loading: false,
      dialogVisible: false,
      addEditFlag: 'add',
      btnList: ['add'],
      formData: {
        dataTypeName: '',
        lowerLimitValue: null,
        lowerLimitResult: '',
        upperLimitValue: null,
        upperLimitResult: ''
      },
      searchFormData: {},
      growthStageList: [],
      varietyList: [],
      dataList: [],
      dataTypeList: [],
      rules: {
        upperLimitResult: [
          { required: true, message: '请选择输入内容', trigger: 'change' }
        ],
        upperLimitValue: [
          { required: true, message: '请选择输入内容', trigger: 'change' }
        ],
        lowerLimitResult: [
          { required: true, message: '请选择输入内容', trigger: 'change' }
        ],
        lowerLimitValue: [
          { required: true, message: '请选择输入内容', trigger: 'change' }
        ],

        dataTypeId: [
          { required: true, message: '请选择数据类型', trigger: 'change' }
        ],
        warningName: [
          { required: true, message: '请选择输入内容', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'codeList'
    ])
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() { // 获取所有数据类型
      this.$set(this.searchFormData, 'plantVarietyId', '')
      this.$set(this.searchFormData, 'growStageId', '')
      let { data: dataTypeList } = await alarmCategoryManagement.getalldatalist();
      this.dataTypeList = dataTypeList || []
      let { data: varietyList } = await varietyManagement.queryByCondition({})
      this.varietyList = varietyList || [];
      let { data: growthStageList } = await growthStageDivision.queryByCondition({})
      this.growthStageList = growthStageList || [];
      if (varietyList.length > 0) {
        this.handleClickVariety(varietyList[0])
      }
      this.queryPageByCondition();
    },
    handleDataType(id) {
      let result = this.dataTypeList.find(obj => obj.dataTypeId == id);
      this.$set(this.form, 'dataTypeName', result.dataTypeName)
    },
    handleClickVariety(row) {
      this.dataList = [];
      this.$set(this.searchFormData, 'plantVarietyId', '')
      this.$set(this.searchFormData, 'growStageId', '')
      this.searchFormData.plantVarietyId = row.plantVarietyId;
      let chooseGrowStage = this.growthStageList.filter(item => {
        return item.plantVarietyId == row.plantVarietyId
      })
      if (chooseGrowStage.length) {
        this.handleClickGrowStage(chooseGrowStage[0])
      } else {
        this.queryPageByCondition();
      }
      this.hasGrowStageFlag = this.isHasGrowStage()
    },
    isHasGrowStage() {
      let id = this.searchFormData.plantVarietyId || ''
      let chooseGrowStage = this.growthStageList.filter(item => {
        return id == item.plantVarietyId
      })
      if (chooseGrowStage.length > 0) {
        return true
      } else {
        return false
      }
    },
    handleClickGrowStage(row) {
      this.searchFormData.growStageId = row.growStageId;
      this.queryPageByCondition();
    },
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      }
      environmentAlarmConfig.queryPageByCondition({ ...params }).then(res => {
        if (res.code == 1) {
          this.dataList = res.data.content || [];
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.$message.warning(res.msg || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    delById(id) {
      if(!(this.codeList.indexOf('delete') !== -1)){
        this.$message.warning('无权限操作')
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let res = await environmentAlarmConfig.delId(id);
        this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg || '操作失败')
        this.queryPageByCondition();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition()
    },
    handleSizeChange(size) {
      this.size = size;
      this.queryPageByCondition();
    },
    onSubmit() {
      if(!(this.codeList.indexOf('add') !== -1)){
        this.$message.warning('无权限操作')
        return
      }
      if (!this.searchFormData.growStageId) {
        this.$message.warning('请选择养殖阶段')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          environmentAlarmConfig.add({ ...this.form, ...this.searchFormData }).then(res => {
            let msg = res.code == 1 ? '操作成功' : '操作失败'
            this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
            if (res.code == 1) {
              this.queryPageByCondition()
              this.isResetForm();
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          return false;
        }
      })
    },
    isResetForm() {
      setTimeout(() => {
        this.$confirm('是否重置表单?', '提示', {
          confirmButtonText: '重置',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$refs.form && this.$refs.form.resetFields()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      }, 500);
    },
    cancel() {
      this.form = {}
      this.$refs.form && this.$refs.form.resetFields()
    },
    //获取选中Btn
    getBtnEvent(flag) {
      if (flag == 'add') {
        this.formData = { ...this.searchFormData };
        this.dialogVisible = true;
      }
      this.addEditFlag = flag
    },
    handleEdit(data) {
      this.formData = JSON.parse(JSON.stringify({ ...data, ...this.searchFormData }));
      this.dialogVisible = true;
      this.addEditFlag = 'edit'
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
::v-deep .tableSlot,
::v-deep .module{
  height: 100% !important;
}
.config {
  width: 100%;
  padding: 15px 0;

  &:nth-child(1) {
    padding-top: 15px;
  }
}

.configTitle {
  display: flex;
  align-items: center;
  line-height: 30px;
  color: #2f6a9b;
  font-weight: bold;

  .el-icon-caret-right {
    color: #4381b5;
    font-size: 24px;
  }

  margin-bottom: 15px;
  font-size: 16px;
  color: #2f6a9b;
}

.gradient-border {
  position: relative;
  /* 确保伪元素能够正确定位 */
  /* 其他样式，如宽度、高度、背景色等 */
}

.gradient-border::after {
  content: '';
  /* 伪元素需要内容来显示，但这里使用空内容 */
  position: absolute;
  /* 绝对定位使伪元素脱离正常文档流 */
  left: 0;
  bottom: 0;
  /* 定位到底部 */
  width: 100%;
  /* 宽度与父元素相同 */
  height: 8px;
  /* 高度设置为所需的边框宽度 */
  background-image:
    repeating-linear-gradient(to right,
      transparent,
      transparent 8px,
      /* 控制虚线间隔 */
      #fff 8px,
      #fff 10px
      /* 控制虚线宽度 */
    ),
    linear-gradient(to right, rgb(32, 119, 153) 50%, rgb(107, 198, 240) 50%);
  /* 先应用渐变背景 */
}

::v-deep .pagination {
  box-shadow: none !important;
}

.top {
  .cropModel {
    display: flex;
    justify-content: flex-start;
    flex-wrap: nowrap;
    margin-bottom: 10px;

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      width: 120px;
      padding: 10px 0;
      margin: 5px 0;
    }

    .tagList {
      width: calc(100% - 120px);
      display: flex;
      justify-content: flex-start;
      flex-wrap: nowrap;
      margin: 5px;
      overflow-y: auto;

      .tag {
        min-width: 150px;
        height: 30px;
        line-height: 30px;
        text-align: center;
        margin-right: 10px;
        border-radius: 2px;
        font-size: 14px;
        border: 1px solid #c1cdda;
        cursor: pointer;
        transition: all 0.2s;
        margin: 5px;

        &:hover {
          background-color: #2f6a9b;
          color: #ffffff;
        }
      }

      .active {
        background-color: #2f6a9b;
        color: #ffffff;
      }
    }
  }
}

.middle {
  .warngingInfo {
    margin-top: 40px;
    padding: 0 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .label {
      color: #2f6a9b;
      font-weight: bold;
      margin-right: 10px;
    }
  }
}

.bottom {
  margin-bottom: 0;

  .dataList {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 20px;
    margin-bottom: 10px;
    background-color: #eff3f5;
    transition: all 0.3s;

    &:nth-child(even) {
      background-color: #dee8f1;
    }

    &:hover {
      background-color: #dde4e7;
    }

    &:last-child {
      margin-bottom: 0;
    }

    .label {
      padding: 10px 15px;
      background-color: #4381b5;
      color: #ffffff;
      display: inline-block;
      border-radius: 4px;
      margin-right: 10px;
      font-size: 12px;
    }
  }
}

.noData {
  line-height: 40px;
}
</style>